﻿using JWT;
using Newtonsoft.Json.Linq;
using Pay.Core;
using Pay.DTO;
using Pay.IService;
using Pay.Service;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace Pay.Token.Controllers {
    /// <summary>
    /// 用户相关
    /// </summary>
    [RoutePrefix("user")]
    public class AccountController : BaseController {
        private readonly ITokenService _iTokenService;
        private readonly IMerchantService _iMerchantService;
        private readonly ISoupTaskService _iSoupTaskService;
        private readonly IShippingAddressService _iShippingAddressService;
        private readonly IPlayingService _iPlayingService;
        private readonly IUserFeedBackService _userFeedBackService;
        private readonly ISettingService _settingService;
        public AccountController(ITokenService iTokenService, IMerchantService iMerchantService, ISoupTaskService iSoupTaskService,
            IShippingAddressService iShippingAddressService, IPlayingService iPlayingService, IUserFeedBackService userFeedBackService, ISettingService settingService) {
            this._iTokenService = iTokenService;
            this._iMerchantService = iMerchantService;
            this._iSoupTaskService = iSoupTaskService;
            this._iShippingAddressService = iShippingAddressService;
            this._iPlayingService = iPlayingService;
            _userFeedBackService = userFeedBackService;
            _settingService = settingService;
        }

        /// <summary>
        /// 用户登录 注册
        /// </summary>
        /// <param name="model">手机号和密码</param>
        /// <returns></returns>
        [Route("login"), HttpPost, AllowAnonymous]
        public ResultMessage<token_info_dto> Login([FromBody]token_login_model model) {
            if (!ModelState.IsValid)
                return ResultToJson.Json<token_info_dto>(ModelError);
            if (string.IsNullOrEmpty(model.mobile_code)) model.mobile_code = "86";
            var member = _iMerchantService.TokenLogin(model.mobile, model.code, model.mobile_code);
            var userToken = new AuthHelper().GetToken(_iTokenService, model.mobile, member.id, member.merchant_no);
            return ResultToJson.Json(userToken);
        }
        /// <summary>
        /// token 注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("register"), HttpPost, AllowAnonymous, Throttle(60 * 60 * 2, 1000)]
        public async Task<ResultMessage<token_info_dto>> RegisterAsync([FromBody]token_register_model model) {
            if (!ModelState.IsValid)
                return ResultToJson.Json<token_info_dto>(ModelError);
            if (string.IsNullOrEmpty(model.mobile_code)) model.mobile_code = "86";
            merchant_dto member = null;
            if (!string.IsNullOrEmpty(model.card_no) && !string.IsNullOrEmpty(model.user_name))
                member = await _iMerchantService.TokenRegisterAsync(model);
            else
                member = _iMerchantService.TokenRegister2Async(model);
            var userToken = new AuthHelper().GetToken(_iTokenService, model.mobile, member.id, member.merchant_no);
            return ResultToJson.Json(userToken);
        }
        /// <summary>
        /// token 密码登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("login_password"), HttpPost, AllowAnonymous]
        public ResultMessage<token_info_dto> LoginByPassword([FromBody]edit_password model) {
            if (!ModelState.IsValid)
                return ResultToJson.Json<token_info_dto>(ModelError);
            model.oem_no = t_RequestMethod.merchant_no;
            var member = _iMerchantService.Login(model.mobile, model.password, model.oem_no);
            var userToken = new AuthHelper().GetToken(_iTokenService, model.mobile, member.id, member.merchant_no);
            return ResultToJson.Json(userToken);
        }
        /// <summary>
        /// token 短信验证码登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("login_code"), HttpPost, AllowAnonymous]
        public ResultMessage<token_info_dto> LoginByCode([FromBody]token_login_model model) {
            if (!ModelState.IsValid)
                return ResultToJson.Json<token_info_dto>(ModelError);
            if (string.IsNullOrEmpty(model.mobile_code)) model.mobile_code = "86";
            var member = _iMerchantService.TokenLoginByCode(model);
            var userToken = new AuthHelper().GetToken(_iTokenService, model.mobile, member.id, member.merchant_no);
            return ResultToJson.Json(userToken);
        }
        /// <summary>
        /// token忘记密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("forget"), HttpPost, AllowAnonymous]
        public ResultMessage<bool> Forget([FromBody]forget_model model) {
            if (!ModelState.IsValid)
                return ResultToJson.Json<bool>(ModelError);
            if (string.IsNullOrEmpty(model.mobile_code)) model.mobile_code = "86";
            model.oem_no = t_RequestMethod.merchant_no;
            if (string.IsNullOrEmpty(model.code)) {
                return ResultToJson.Json<bool>("验证码不存在");
            }
            _settingService.ValidCode(model.mobile, model.code, "token_forget");
            var result = _iMerchantService.Forget(model);
            if (result)
                _settingService.RemoveCode(model.mobile, "token_forget");

            return ResultToJson.Json<bool>(result ? 1000 : 1001, result ? "重设密码成功" : "重设失败", result);
        }
        /// <summary>
		/// 获取登录用户的信息
		/// </summary>
		/// <returns>The user.</returns>
		[Route("user"), HttpGet]
        public async Task<ResultMessage<token_user_info>> GetUser() {
            var user = _iMerchantService.GetTokenUser(UserId);
            return await ResultToJson.JsonAsync(user);
        }
        /// <summary>
		/// 获取登录用户的实名信息
		/// </summary>
		/// <returns>The user.</returns>
		[Route("auth"), HttpGet]
        public async Task<ResultMessage<authinfo_req>> GetUserAuth() {
            var user = _iMerchantService.GetAuth(UserId).ToDtoObject<authinfo_req>();
            return await ResultToJson.JsonAsync(user);
        }
        /// <summary>
        /// 修改昵称
        /// </summary>
        /// <param name="nick_name">昵称</param>
        /// <returns></returns>
        [Route("nick_name"), HttpPost]
        public async Task<ResultMessage<bool>> UserNickName([FromBody] JObject nick_name) {
            var nick = GetJsonValue<string>("nick_name", nick_name);
            var result = _iMerchantService.SaveUserNickName(nick, UserId, t_RequestMethod.merchant_no);
            return await ResultToJson.JsonAsync(result ? "修改成功" : "修改失败", result);
        }
        /// <summary>
		/// 保存头像
		/// </summary>
		/// <returns>The photo.</returns>
		/// <param name="photo">调用上传图片接口返回的头像路径.</param>
		[Route("photo"), HttpPost]
        public async Task<ResultMessage<bool>> SavePhoto([FromBody] JObject photo) {
            var image_path = GetJsonValue<string>("photo", photo);
            var member = _iMerchantService.Get(UserId);
            if (!string.IsNullOrEmpty(member.photo) && !string.IsNullOrEmpty(image_path) && member.photo != image_path) {
                var data = new t_delete_file_model();
                data.file_names.Add(new file_name_item { file_name = member.photo });
                data.method = t_RequestMethod.DELETE_FILE;
                var d_result = await ChannelApi.Current.PostApi<result_base>(data);
            }
            member.photo = image_path;
            bool result = _iMerchantService.UpdateUser(member);
            return ResultToJson.Json(result ? "保存成功" : "保存失败", result);
        }
        /// <summary>
        /// 实名认证
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("no_card"), HttpPost]
        public async Task<ResultMessage<bool>> NoCard([FromBody]token_cardno_model model) {
            if (!ModelState.IsValid)
                return ResultToJson.Json<bool>(ModelError);
            var result = await _iMerchantService.VerificationNoCard(model, UserId);
            return await ResultToJson.JsonAsync(result ? "实名认证成功" : "实名认证失败", result);
        }
        /// <summary>
        /// 邀请码认证
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("invitation_code"), HttpPost]
        public async Task<ResultMessage<bool>> Invitation([FromBody]token_invitation_code_model model) {
            if (!ModelState.IsValid)
                return ResultToJson.Json<bool>(ModelError);
            var result = _iMerchantService.InvitationCode(model, UserId);
            return await ResultToJson.JsonAsync(result ? "验证成功" : "验证失败", result);
        }
        /// <summary>
        /// 用户反馈
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("free_back"), HttpPost]
        public async Task<ResultMessage<bool>> UserFreeBack([FromBody]freeback_model model) {
            if (!ModelState.IsValid)
                return ResultToJson.Json<bool>(ModelError);
            var result = _userFeedBackService.Add(new user_feedback_dto { createtime = DateTime.Now, userid = UserId, usercontact = model.contact, user_feedback_content = model.content });
            return await ResultToJson.JsonAsync(result > 0 ? "保存成功" : "保存失败", result > 0);
        }
        /// <summary>
        /// 每日登录
        /// </summary>
        /// <returns></returns>
        [Route("day_login"), HttpPost]
        public async Task<ResultMessage<bool>> UserDayLogin() {
            _iPlayingService.DealUserGuess(UserId);
            var result = await _iSoupTaskService.TaskRecive(UserId, ETaskType.Login);
            return await ResultToJson.JsonAsync(result);
        }
        /// <summary>
        /// 新增/编辑收货地址
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("save_address"), HttpPost]
        public async Task<ResultMessage<bool>> AddAddress([FromBody]shipping_address_dto model) {
            if (!ModelState.IsValid)
                return await ResultToJson.JsonAsync<bool>(ModelError);

            model.user_id = UserId;
            model.card_negative = model.card_positive = string.Empty;
            if (string.IsNullOrEmpty(model.id_card) || string.IsNullOrEmpty(model.real_name)) {
                if (model.id > 0) {
                    var item = _iShippingAddressService.Get(model.id);
                    model.id_card = item.id_card;
                    model.real_name = item.real_name;
                } else {
                    var auth = _iMerchantService.GetAuth(UserId);
                    if (auth != null) {
                        model.id_card = auth.id_card;
                        model.real_name = auth.account_name;
                    } else
                        model.id_card = model.real_name = string.Empty;
                }
            }
            int result = 0;
            if (model.id == 0)
                result = _iShippingAddressService.Add(model);
            else
                result = _iShippingAddressService.Update(model);
            return await ResultToJson.JsonAsync(result > 0 ? "保存成功" : "保存失败", result > 0);

        }

        /// <summary>
        /// 收货地址列表
        /// </summary>
        /// <returns></returns>
        [Route("get_address"), HttpGet]
        public async Task<ResultMessage<List<shipping_address_dto>>> GetAddress() {
            var list = _iShippingAddressService.GetAddressByUser(UserId).ToList();
            return await ResultToJson.JsonAsync(list);
        }
        /// <summary>
        /// 地址详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("get_address_detail"), HttpGet]
        public async Task<ResultMessage<shipping_address_dto>> GetAddressDetail(long id) {
            var address = _iShippingAddressService.Get(id);
            if (address.user_id != UserId)
                return await ResultToJson.JsonAsync<shipping_address_dto>("获取失败，不是你的收货地址");
            return await ResultToJson.JsonAsync("获取成功", address);
        }
        /// <summary>
        /// 默认收货地址
        /// </summary>
        /// <returns></returns>
        [Route("address_default"), HttpGet]
        public ResultMessage<shipping_address_dto> GetDefaultAddress() {
            var address = _iShippingAddressService.GetByDefault(UserId);
            if (address == null) return ResultToJson.Json("获取成功", address);
            if (address.user_id != UserId)
                return ResultToJson.Json<shipping_address_dto>("获取失败，不是你的收货地址");
            return ResultToJson.Json("获取成功", address);
        }
        /// <summary>
        /// 删除收货地址
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("del_address"), HttpGet]
        public async Task<ResultMessage<bool>> DelAddress(long id) {
            var result = _iShippingAddressService.DeleteAdress(id);
            return await ResultToJson.JsonAsync(result > 0 ? "删除成功" : "默认地址不能删除", result > 0);
        }
        /// <summary>
        /// 刷新登录，如果返回的data是null时，就跳到登录页面做手动登录，
        /// 不要在Header中增加Authorization，不然反而会出错。这个接口是不需要授权的
        /// </summary>
        /// <returns>The refresh.</returns>
        /// <param name="access_token">上次使用的access_token</param>
        [Route("refresh"), HttpPost]
        [AllowAnonymous]
        public ResultMessage<token_info_dto> Refresh([FromBody] JObject access_token) {
            var token = GetJsonValue<string>("access_token", access_token);
            AuthHelper authHelper = new AuthHelper();
            string decodedJwt = authHelper.ValidateToken(token);
            if (!string.IsNullOrEmpty(decodedJwt)) {
                dynamic root = JObject.Parse(decodedJwt);
                long user_id = long.Parse(root.merchant_id.ToString());
                bool pool = false;
                var token_info = _iTokenService.Get(user_id, out pool);
                if (!pool)
                    return ResultToJson.Json<token_info_dto>(600, "刷新异常");
                if (token_info == null || (token_info != null && token_info.access_token != token))
                    return ResultToJson.Json<token_info_dto>(600, "登录异常");

                return ResultToJson.Json(token_info);
            } else {
                var urlEncoder = new JwtBase64UrlEncoder();
                var payload = urlEncoder.Decode(token.Split('.')[1]);
                decodedJwt = Encoding.UTF8.GetString(payload);
                dynamic root = JObject.Parse(decodedJwt);
                long user_id = long.Parse(root.merchant_id.ToString());
                bool pool = false;
                var token_info = _iTokenService.Get(user_id, out pool);
                if (!pool)
                    return ResultToJson.Json<token_info_dto>(600, "刷新异常2");
                if (token_info == null || (token_info != null && token_info.access_token != token))
                    return ResultToJson.Json<token_info_dto>(600, "登录异常2");
                var member = _iMerchantService.Get(token_info.id);
                var userToken = new AuthHelper().GetToken(_iTokenService, member.mobile, member.id, member.merchant_no);
                return ResultToJson.Json(userToken);
            }
        }
        /// <summary>
        /// 发起实人认证
        /// </summary>
        /// <returns></returns>
        [Route("get_verify_token"), HttpGet]
        public async Task<ResultMessage<VerifyResult>> GetVerifyToken() {
            var data =  await _iMerchantService.GetVerifyToken(UserId);
            return ResultToJson.Json<VerifyResult>(data);
        }
    }
}